import * as step from '@flow-step/step-toolkit'
import * as path from 'path'
import * as fs from 'fs'
import { simpleGit, SimpleGit } from 'simple-git';
import {SetSSHPrivateKey} from "./sshKey"
import {replaceEnvVar} from './util'


export async function gitTag() : Promise<void>{
    let projectDir = process.env.PROJECT_DIR as string;
    let repoDirName = path.basename(projectDir);  //the repo we work on
    SetSSHPrivateKey(repoDirName);

    process.env.GIT_SSL_NO_VERIFY = '1';
    const git: SimpleGit = simpleGit();
    git.env(process.env);
    await git.addConfig('user.name','rdc')
    await git.addConfig('user.email','rdc@alibaba-inc.com')
    await git.cwd(process.env.PROJECT_DIR as string);

    const gitTagInput = process.env.GIT_TAG as string;
    let realTag = replaceEnvVar(gitTagInput)
    let gitTagMsg = process.env.GIT_TAG_MSG;
    step.info(' ================================git tag started=======================================')
    if (gitTagMsg == undefined){
        try{
            await git.tag(['-f',realTag])
            step.info(`git tag ${realTag}`)
        } catch (error) {
            step.error(`git tag ${realTag} failed`)
            throw error;
        }
    }else{
        gitTagMsg = replaceEnvVar(gitTagMsg)
        try {
            await git.tag(['-f', realTag, '-m', gitTagMsg])
            step.info(`git tag ${realTag} with message ${gitTagMsg}`)
        } catch (error:any) {
            step.error(`git tag ${realTag} with message ${gitTagMsg} failed`)
            throw error;
        }
    }

    try {
        await git.push(['origin', realTag]);
        step.info(`git push origin tag ${realTag} succeeded`);
    }
    catch (error:any) {
        if (error.message.includes("not found")){
            step.error(`repository does not exist, or the user has no permission`);
        }
        step.error(`git push origin tag ${realTag} failed`);
        throw error;
    }
}

export function getRealGitTag(gitTagInput: string): string{
    const regex = /\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
    return gitTagInput.replace(regex, (_, envVar) => {
        return process.env[envVar] || '';
    });
}



